package com.sardine.base.esm.session.defaults;

import com.sardine.base.esm.executor.EsmExecutor;
import com.sardine.base.esm.session.Configuration;
import com.sardine.base.esm.session.EsmExecutorType;
import com.sardine.base.esm.session.EsmSession;
import com.sardine.base.esm.session.EsmSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/5/22
 * Time:10:52
 *
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class DefaultEsmSessionFactory implements EsmSessionFactory {
    private static final Logger logger = LoggerFactory.getLogger(DefaultEsmSessionFactory.class);

    private final Configuration configuration;

    public DefaultEsmSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public EsmSession openSession() {
        return openSessionFromDataSource(configuration.getDefaultEsmExecutorType());
    }

    @Override
    public EsmSession openSession(EsmExecutorType esmExecutorType) {
        return openSessionFromDataSource(esmExecutorType);
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }


    private EsmSession openSessionFromDataSource(EsmExecutorType execType) {
        try {
            final EsmExecutor executor = configuration.newExecutor(execType);
            return new DefaultEsmSession(configuration, executor);
        } catch (Exception e) {
            throw new RuntimeException("Error opening session.  Cause: " + e, e);
        }
    }
}
